package com.glacier.cloud.gateway.predicate;

import jakarta.validation.constraints.NotEmpty;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.handler.predicate.AbstractRoutePredicateFactory;
import org.springframework.cloud.gateway.handler.predicate.GatewayPredicate;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.server.ServerWebExchange;

import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.function.Predicate;

/**
 * date 2024-01-31 17:10
 * 自定义断言
 * 参照 QueryRoutePredicateFactory
 *
 * @author glacier
 * @version 1.0
 */
@Slf4j
public class GlacierRoutePredicateFactory extends AbstractRoutePredicateFactory<GlacierRoutePredicateFactory.Config> {
    public static final String PARAM_KEY = "param";
    public static final String REGEXP_KEY = "regexp";

    public GlacierRoutePredicateFactory() {
        super(Config.class);
    }

    @Override
    public List<String> shortcutFieldOrder() {
        return Arrays.asList("param", "regexp");
    }


    @Override
    public Predicate<ServerWebExchange> apply(final Config config) {
        return new GatewayPredicate() {
            @Override
            public boolean test(ServerWebExchange exchange) {
                if (!StringUtils.hasText(config.regexp)) {
                    return exchange.getRequest()
                            .getQueryParams()
                            .containsKey(config.param);
                } else {
                    List<String> values = exchange.getRequest()
                            .getQueryParams()
                            .get(config.param);
                    if (values == null) {
                        return false;
                    } else {
                        Iterator<String> iterator = values.iterator();

                        String value;
                        do {
                            if (!iterator.hasNext()) {
                                return false;
                            }

                            value = iterator.next();
                        } while (value == null || !value.matches(config.regexp));

                        return true;
                    }
                }
            }

            @Override
            public Object getConfig() {
                return config;
            }

            @Override
            public String toString() {
                return String.format("Query: param=%s regexp=%s", config.getParam(), config.getRegexp());
            }
        };
    }


    @Validated
    @Data
    @NoArgsConstructor
    public static class Config {
        private @NotEmpty String param;
        private String regexp;
    }
}
